//
//  DCIMGroupChatSettingViewController.m
//  xmppBase
//
//  Created by striby on 16/1/13.
//  Copyright © 2016年 com.dc. All rights reserved.
//

#import "DCIMGroupChatSettingViewController.h"

static int IconNumForOneRow = 5;
static int IconNameHeight =20;

@interface DCIMGroupChatSettingViewController ()
{
    
    
    CGFloat iconViewWidth;
    
    int rowNum;
    
    UIView * iconsView;
    
    UITextField * discussionTextField;
    
    NSMutableArray * groupUsers ;
}
@end

@implementation DCIMGroupChatSettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    

    
    iconViewWidth = [UIScreen mainScreen].bounds.size.width/IconNumForOneRow;
    
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, DCDeviceWidth, DCDeviceHeight)];
    self.tableView.delegate=self;
    self.tableView.dataSource =self;
    self.tableView.backgroundColor=[UIColor groupTableViewBackgroundColor];
    
    
    [self.view addSubview:self.tableView];
    
    [self.tableView setContentInset:UIEdgeInsetsMake(0, 0, TabBarHeight, 0)];
    
    [self.tableView setShowsVerticalScrollIndicator:NO];
    
    self.tableView.separatorInset = UIEdgeInsetsZero;
    
//    self.title = @"讨论组设置";
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveMemebers:) name:kDidFetchModeratorList object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(joinedRoomFechInfo) name:kDidJoinGroupSuccessed object:nil];
    
    if ([self.room isJoined]) {
        [self joinedRoomFechInfo];
    }
}

-(void)joinedRoomFechInfo
{
//    [[DCIMGroupManager shareInstance]queryInfoJid:self.room.roomJID.full];
    
    [self.room fetchMembersList];
    [self.room fetchModeratorsList];
    [self.room fetchConfigurationForm];
}

-(void)didReceiveMemebers:(NSNotification*)noti
{
    if (groupUsers==nil) {
        groupUsers = [[NSMutableArray alloc]init];
    }
    else
    {
        [groupUsers removeAllObjects];
    }
    
 
    
    NSArray * arr = noti.object;
        for (int i=0; i<arr.count; i++) {
            
            [groupUsers addObject:arr[i]];
        }
    
       [groupUsers addObject:@"+"];
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    });
}



-(void)didFetchConfigurationForm:(NSNotification*)noti
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
       
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    });
    
}

#pragma mark iconView
-(UIView*)createIconsViewForView
{
    
    UIView * iconView = [[UIView alloc]initWithFrame:CGRectZero];
    
    int line = 0;
    
    CGFloat btnWidth = iconViewWidth*0.7;
    
    CGFloat btnMargin = iconViewWidth*0.15;
    
    UIView * lastView;
    
 
    for (int i=0; i<groupUsers.count; i++)
    {
        
        DCUserInfoButton * btn = [[DCUserInfoButton alloc]initWithFrame:CGRectMake((i%IconNumForOneRow)*iconViewWidth+btnMargin, btnMargin+line*(iconViewWidth), btnWidth, btnWidth)];
        btn.tag = i;
        
        
        [iconView addSubview:btn];
        
        
        UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(btn.frame.origin.x, btn.frame.origin.y+btnWidth, btnWidth, IconNameHeight)];
        label.textAlignment = NSTextAlignmentCenter;
        
        label.font = [UIFont systemFontOfSize:12];
        label.textColor = [UIColor darkGrayColor];
        [iconView addSubview:label];
        
        
        if (i==groupUsers.count-1) {
            btn.backgroundColor = [UIColor lightGrayColor];
            
            btn.layer.masksToBounds=YES;
            btn.layer.cornerRadius=5;
            [btn setImage:[UIImage imageNamed:@"add"] forState:UIControlStateNormal];
            label.text = @"";
            
            lastView=label;
            
            [btn addTarget:self action:@selector(inviteFriend) forControlEvents:UIControlEventTouchUpInside];
        }
        else
        {
           
            
            [btn setBackgroundImage:[UIImage imageNamed:@"defaultUserIcon"] forState:UIControlStateNormal];
            label.text = @"";
            [btn addTarget:self action:@selector(lookForUserInfo:) forControlEvents:UIControlEventTouchUpInside];
            
            __weak typeof (btn) blockBtn = btn;
            __weak typeof (label) blockLabel = label;
            
            
            DDXMLElement * ele = groupUsers[i];
            blockLabel.text = [[ele attributeForName:@"nick"] stringValue];
            blockBtn.userInfo = nil;
            
            
            lastView = label;
            
            
            
            if (i%IconNumForOneRow==IconNumForOneRow-1) {
                line++;
            }
        }
    }
    
    [iconView setFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, lastView.frame.size.height+lastView.frame.origin.y+btnMargin)];
    
    return iconView;
}

-(void)inviteFriend
{
    DCIMFriendListViewController * vc = [[DCIMFriendListViewController alloc]init];
    
    vc.friendListType = DCFriendListTypeInviteFriends;
    
    vc.extraInfo = self.room;
    
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)lookForUserInfo:(UIButton*)sender
{
    
    DDXMLElement * ele = groupUsers[sender.tag];
    
    NSString * userID =  [[ele attributeForName:@"jid"] stringValue];
    
    DCIMUserInfoViewController * vc =[[DCIMUserInfoViewController alloc]init];
    
    vc.userJid = [XMPPJID jidWithString:userID];
    
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - Table view



-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 18;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, DCDeviceWidth, 18)];
    view.backgroundColor = [UIColor clearColor];
    return view;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, DCDeviceWidth, 18)];
    view.backgroundColor = [UIColor clearColor];
    return view;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        
        if (self.isSettingDiscussName) {
            return 40;
        }
        
        iconsView = [self createIconsViewForView];
        return iconsView.bounds.size.height;
    }
    
    return 40;
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableVie
{
    
    if (self.isSettingDiscussName) {
        return 1;
    }
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section==1) {
        return 2;
    }
    else
    {
        return 1;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" ];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        for (UIView * view in cell.contentView.subviews) {
            [view removeFromSuperview];
        }
        
        if (!self.isSettingDiscussName) {
            [cell.contentView addSubview:iconsView];
        }
        else
        {
            discussionTextField= [[UITextField alloc]initWithFrame:CGRectMake(15, 5, cell.contentView.frame.size.width-30, 30)];
            discussionTextField.text = [[DCIMGroupManager shareInstance]getRoomNameWithRoomJid:self.room.roomJID];
            [cell.contentView addSubview:discussionTextField];
            [discussionTextField becomeFirstResponder];
        }
        
        
        return cell;
    }
    
    else
    {
        DCSettingTableViewCell * cell = [[[NSBundle mainBundle]loadNibNamed:@"DCSettingTableViewCell" owner:nil options:nil]lastObject];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (indexPath.row==0) {
            cell.CellTitle.text = @"群名称";
            
            cell.CellDetail.text = [[DCIMGroupManager shareInstance]getRoomNameWithRoomJid:self.room.roomJID];;
            
        }
        else
        {
            cell.CellTitle.text = @"清空聊天记录";
        }
        
        return cell;
        
    }
}


/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
